<?php
namespace app\common\model;

use think\Cache;
use think\Db;
use think\Model;
use think\View;
/**
 * @property mixed id
 */
class UserView extends Model
{
    /**
     * 模型名称
     * @var string
     */
    protected $name = 'user_view';
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected $updateTime = false;

    /**
     * 关联表
     * @param  string $table_name [关联表名]
     * @return \think\model\relation\HasOne
     */
    protected function unionTable($table_name)
    {
        return $this->hasOne($table_name . 'Model', 'object_id');
    }

    /**
     * thumbnail 自动转化图片地址为绝对地址
     * @param $value
     * @return string
     */
    public function getThumbnailAttr($value)
    {
        if (!empty($value)) {
            $value = request()->domain().'/'.($value);
        }

        return $value;
    }

    /**
     * url   自动转化
     * @param $value
     * @return string
     */
    public function getUrlAttr($value)
    {
        $url = json_decode($value, true);
        if (!empty($url)) {
            $url = url($url['action'], $url['param'], true, true);
        } else {
            $url = '';
        }
        return $url;
    }

    /**
     * 获取查看内容
     * @param  array $data [select,find查询结果]
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getView($data)
    {
        if (!is_string($data[0])) {
            foreach ($data as $key => $value) {
                $where[$value['table_name']][] = $value['object_id'];
            }
            foreach ($where as $key => $value) {
                $favoriteData[] = $this->unionTable($key)->select($value);
            }
        } else {
            $favoriteData = $this->unionTable($data['table_name'])->find($data['object_id']);
        }

        return $favoriteData;
    }

    /**
     * 添加查看
     * @param $data
     * @return bool
     */
    public function addView($data)
    {
        //获取查看内容信息
        $Favorite =$this->save($data);
        return $Favorite;
    }


    /**
     * 查看总数
     * @param $object_id
     * @param $type
     * @return int|string
     * @throws \think\Exception
     */
    public static function favTotal($object_id, $type){
        return self::where(['object_id' => $object_id, 'table_name' =>$type])->count();
    }
}
